package com.itheima.health.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.common.MessageConst;
import com.itheima.health.dao.CheckgroupDao;
import com.itheima.health.dao.SetmealDao;
import com.itheima.health.dao.SetmealGroupDao;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.*;
import com.itheima.health.result.PageResult;
import com.itheima.health.result.QueryPageBean;
import com.itheima.health.service.SetmealService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private CheckgroupDao checkGroupDao;
    @Autowired
    private SetmealGroupDao setmealGroupDao;
    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        log.info("[检查项-分页查询]data：{}",queryPageBean);
        //使用分页插件
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        // 分页查询数据库
        Page<Setmeal> page = setmealDao.PageSelect(queryPageBean.getQueryString());
        //封装分页数据
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 新增套餐
     * @param setmeal checkgroupIds
     */
    @Override
    public void insert(Setmeal setmeal,Integer[] checkgroupIds) {
        setmealDao.insert(setmeal);

        Integer id = setmeal.getId();
        List<CheckGroup> checkGroups = new ArrayList<>();
        if (checkgroupIds != null && checkgroupIds.length != 0) {
            for (Integer checkgroupId : checkgroupIds) {
                CheckGroup checkGroup = checkGroupDao.SelectById(checkgroupId);
                SetmealGroup setmealGroup = new SetmealGroup();
                setmealGroup.setSetmealId(id);
                setmealGroup.setCheckgroupId(setmeal.getId());
                BeanUtils.copyProperties(checkGroup, setmealGroup);
                setmealGroupDao.insert(setmealGroup);
                checkGroups.add(checkGroup);
            }
            setmeal.setCheckGroups(checkGroups);
        } else {
            throw new BusinessRuntimeException(MessageConst.ADD_CHECKGROUP_FAIL);
        }
    }
}
